from typing import List
import openpyxl
from collections import Counter
from wordcloud import WordCloud


def save_to_excel(danmakus: List[str], filename: str):
    """Calculates word frequency and saves the danmaku and frequencies to an Excel file."""
    # Calculate word frequency
    all_text = " ".join(danmakus)
    word_counts = Counter(all_text.split())  # Simple split, can be improved

    # Create a new workbook and select the active sheet
    wb = openpyxl.Workbook()
    sheet = wb.active
    sheet.title = "Danmaku Analysis"

    # Write headers
    sheet["A1"] = "Danmaku"
    sheet["B1"] = "Word"
    sheet["C1"] = "Frequency"

    # Write danmakus
    for i, danmaku in enumerate(danmakus, start=2):
        sheet[f"A{i}"] = danmaku

    # Write word frequencies
    for i, (word, count) in enumerate(word_counts.most_common(), start=2):
        sheet[f"B{i}"] = word
        sheet[f"C{i}"] = count

    # Save the workbook
    wb.save(filename)


def generate_word_cloud(danmakus: List[str], filename: str):
    """Generates a word cloud from a list of danmaku and saves it to a file."""
    text = " ".join(danmakus)
    wordcloud = WordCloud(
        width=800,
        height=400,
        background_color="white",
        font_path="msyh.ttc"  # Specify a font that supports Chinese characters
    ).generate(text)
    wordcloud.to_file(filename)